package com.cyh.pangu.ds;

public class MyListDemo {

    private MyListNode head;
    private MyListNode last;

    private int size;

    public void insert(int data, int index) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("超出下标");
        }

        MyListNode dataNode = new MyListNode(data);
        if (size == 0) {
            head = dataNode;
            last = dataNode;
        } else if (index == size) {
            last.next = dataNode;
            last = dataNode;
        } else {
            MyListNode preNode = get(index - 1);
            dataNode.next = preNode.next;
            preNode.next = dataNode;
        }
        size++;
    }

    public  MyListNode remove(int index) {
        if (index < 0 || index > size - 1) {
            throw new IndexOutOfBoundsException("超出下标");
        }
        MyListNode removeNode = null;
        if (index == 0) {
            removeNode = head;
            head = head.next;
        } else if (index == size - 1) {
            MyListNode data = get(index - 1);
            removeNode = data.next ;
            data.next = null;
            last = data;
        } else {
            MyListNode data = get(index - 1);
            removeNode = data.next;
            data.next = data.next.next;
        }

        size--;
        return removeNode;
    }

    public MyListNode get(int index) {
        if (index < 0 || index > size -1) {
            throw  new IndexOutOfBoundsException("超出index范围");
        }
        MyListNode data = head;
        for (int i = 0; i < index; i++) {
            data = data.next;
        }
        return data;
    }

    public void output() {
        MyListNode first = head;
        StringBuilder sb = new StringBuilder();
        while (first != null) {
            sb.append(first.data + ",");
            first = first.next;
        }
        System.out.println("sb:" + sb.toString());
    }

    static class MyListNode {
        int data;
        MyListNode next;
        public MyListNode(int data) {
            this.data = data;
        }
    }
    public static void main(String[] args) {
        MyListDemo myListDemo = new MyListDemo();
        myListDemo.insert(3, 0);
        myListDemo.insert(4, 1);
        myListDemo.insert(5, 2);
        myListDemo.insert(6, 3);
        myListDemo.insert(7, 4);
        myListDemo.insert(12,1);
        myListDemo.output();
        System.out.println("1---------------------");
        MyListDemo.MyListNode myListNode = myListDemo.get(3);
        if (myListNode != null) {
            System.out.println("myListNode.data:" + myListNode.data);
        } else {
            System.out.println("myListNode data is null");
        }

        System.out.println("2---------------------");
        myListDemo.remove(2);
        myListDemo.remove(3);
        myListDemo.output();

    }
}
